package com.julian.warehouse.activity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import com.julian.warehouse.R;
import com.julian.warehouse.adapter.RecordsLvAdapter;
import com.julian.warehouse.base.SPBaseActivity;
import com.julian.warehouse.bean.GoodsBean;
import com.julian.warehouse.bean.RecordsBean;
import com.julian.warehouse.database.GoodsTable;
import com.julian.warehouse.database.MyDBOpenHelper;
import com.julian.warehouse.database.RecordsTable;
import com.julian.warehouse.utils.MyLog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RecordsActivity extends SPBaseActivity {

    private SQLiteDatabase db;
    private ListView lv;
    private List<RecordsBean> list;
    private RecordsLvAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        super.init();
        setHeadTitle(true,"出入库记录");
    }

    @Override
    public void initView() {
        lv = (ListView) findViewById(R.id.lv);

    }

    @Override
    public void initData() {
        list = new ArrayList<>();
        adapter = new RecordsLvAdapter(this, list);
        lv.setAdapter(adapter);

        MyDBOpenHelper myDBOpenHelper = new MyDBOpenHelper(this);
        db = myDBOpenHelper.getReadableDatabase();
        queryAll();
    }

    @Override
    public void initEvent() {

    }


    private void queryAll(){
        //上面的查询方法比较烦，但不易出错
        String sql = "select * from "+ RecordsTable.TBL_NAME;
        Cursor cursor = db.rawQuery(sql, null);
        list.clear();
        while(cursor.moveToNext()){
            RecordsBean recordsBean = new RecordsBean();
            recordsBean.setGname(cursor.getString(cursor.getColumnIndex(RecordsTable.COL_GNAME)));
            recordsBean.setCtime(cursor.getString(cursor.getColumnIndex(RecordsTable.COL_CTIME)));
            recordsBean.setCount(cursor.getInt(cursor.getColumnIndex(RecordsTable.COL_COUNT)));
            recordsBean.setFlag(cursor.getInt(cursor.getColumnIndex(RecordsTable.COL_FLAG)));
            recordsBean.setResult(cursor.getString(cursor.getColumnIndex(RecordsTable.COL_RESULT)));
            list.add(recordsBean);
        }
        cursor.close();
        //db.close();

        Collections.reverse(list);

        MyLog.i("AA","当前记录"+list.toString());
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }
}
